// 云函数入口文件
const cloud = require('wx-server-sdk')
const md5 = require('md5-node');
// 初始化 cloud
cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database();

// 云函数入口函数
exports.main = async (event, context) => {
  const openId = event.userInfo.openId;
  const wifiName = event.wifiName;
  const wifiPwd = event.wifiPwd;
  let qrMd5 = md5(openId + wifiName + wifiPwd);//生成MD5

  let res = await db.collection('md5_index').where({
    qrMd5
  }).get();
  if (res.data.length != 0) {//判断图片是否存在
    return res.data[0].imgUrl
  } else {
    //生成小程序码
    try {
      const qrResult = await cloud.openapi.wxacode.getUnlimited({
        scene: qrMd5,
        page: "pages/connect/connect"
      })
      //获取当前时间
      function format(val) {
        return val < 10 ? `0${val}` : val
      }
      let myDate = new Date();
      let year = format(myDate.getFullYear()); //获取当前年
      let mon = format(myDate.getMonth() + 1); //获取当前月
      let date = format(myDate.getDate()); //获取当前日
      let hours = format(myDate.getHours()); //获取当前小时
      let minutes = format(myDate.getMinutes()); //获取当前分钟
      let seconds = format(myDate.getSeconds()); //获取当前秒
      let now = `${year}${mon}${date}${hours}${minutes}${seconds}`;
      //将图片上传
      let img = await cloud.uploadFile({
        cloudPath: `${now}-${openId}-${format(parseInt(Math.random() * 60))}.png`,
        fileContent: qrResult.buffer
      })

      //将md5信息添加到数据库
    db.collection('md5_index').add({
        data: {
          qrMd5,
          openId,
          wifiName,
          wifiPwd,
          imgUrl: img.fileID,
          time: 0,
          lastDate: 0,
        }
      })
      return img.fileID;
    } catch{
      err => {
        return err;
      }
    }
  }
}